﻿using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;

namespace Wild2.Models.GeoIP
{
    public class GeoIP
    {
        public static string GetLocale()
        {
            String locale = "default";
            String ipString = HttpContext.Current.Request.UserHostAddress;
            if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) ipString = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ipString != null && System.Text.RegularExpressions.Regex.IsMatch(ipString, "(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9])[.]){3}(([2]([0-4][0-9]|[5][0-5])|[0-1]?[0-9]?[0-9]))"))
            {
                Int64 ip = Convertor.ToInt(ipString);
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnect"].ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT GeoIPCountries.code FROM GeoIPCountries INNER JOIN GeoIPCountriesIP ON GeoIPCountries.ID = GeoIPCountriesIP.country_id WHERE (@IP > GeoIPCountriesIP.begin_ip) AND (@IP < GeoIPCountriesIP.end_ip)", conn))
                    {
                        cmd.Parameters.Add("@IP", System.Data.SqlDbType.BigInt).Value = ip;
                        cmd.Connection.Open();
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                locale = reader["code"].ToString();
                            }
                        }
                        cmd.Connection.Close();
                    }
                }
            }
            return locale;
        }
    }
}